<?php
/**
 * bs多规格sku商城系统
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站地址: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2024/12/18
 * 描述:
 */

namespace app\result;

use app\model\auto\RechargeLog;
use app\model\order\Order;
use app\model\user\User;
use app\result\order\OrderResult;
use app\service\CreditService;
use app\service\LockService;
use app\service\PaymentService;
use think\facade\Db;

class PaymentResult extends BaseResult
{
    public function payment_list($user_id, $args = [])
    {
        $from = $args['from'] ?? '';
        $paymentMethods = [
            //['value' => '1', 'name' => '微信支付'],
            // ['value' => '2', 'name' => '支付宝'],
            //  ['value' => '3', 'name' => '转账支付', 'qr_code' => 'http://xcx996.test.top/assets/qrcode/wx.png'],
        ];
        $setting = (new SettingResult())->get_value('payment');
        if (!empty($setting['wechat_open'])) {
            $paymentMethods[] = [
                'value' => '1',
                'name' => '微信支付',
            ];
        }
        if (!empty($setting['alipay_open'])) {
            $paymentMethods[] = [
                'value' => '2',
                'name' => '支付宝',
            ];
        }
        if (!empty($setting['offline_open'])) {
            $paymentMethods[] = [
                'value' => '3',
                'name' => '线下支付',
                'qr_code' => $setting['offline_qrcode'] ?? '',
            ];
        }
        if (!empty($setting['balance_open']) && $from !== 'recharge') {
            $credit = (new User())->get_value(['user_id' => $user_id], 'credit');
            $paymentMethods[] = [
                'value' => '4',
                'name' => '余额支付' . '(账户剩余￥' . $credit . ')',
            ];
        }
        if (!empty($setting['cod_open'])) {
            $paymentMethods[] = [
                'value' => '5',
                'name' => '货到付款',
            ];
        }

        //bs_log($setting, 'payment_list', 'payment_list.log');
        return $paymentMethods;
    }

    public function pay($user_id, $args = [])
    {
        $order_sn = $args['order_sn'] ?? '';
        if (!$order_sn) {
            return self::error_return('请选择订单');
        }
        $pay_way = intval($args['pay_way'] ?? 0);
        if (!$pay_way) {
            return self::error_return('请选择支付方式');
        }
        $order = (new Order())->data_get(['order_sn' => $order_sn]);
        if (!$order) {
            return self::error_return('订单不存在');
        } elseif ($order['pay_status'] == 1) {
            return self::error_return('订单已支付');
        } elseif ($order['order_status'] !== 0) {
            return self::error_return('订单状态不支持支付');
        }
        if ($pay_way == 2) {
            $req = (new PaymentService())->alipay([
                'order_sn' => $order_sn,
                'order_amount' => $order['order_pay_price'],
                'subject' => '商品支付',
                'user_id' => $user_id,
            ]);
            $domain = request()->domain();
            return self::success_return('请求成功，请支付', [
                'order_sn' => $order_sn,
                'params' => $req,
                'url' => $domain . '/api/payment/cashier?order_sn=' . $order_sn . '&title=收银台&api_base_url=' . $domain . '&token=' . ($args['token'] ?? '')
            ]);
        }
        if ($pay_way == 3) {
            try {
                Db::startTrans();
                $res = (new Order())->data_update(['order_sn' => $order_sn], [
                    'pay_time' => date('Y-m-d H:i:s'),
                    'pay_status' => 0,
                    'pay_type' => $pay_way,
                    'pay_amount' => $order['total_price'],
                    'order_status' => 7,//待审核
                ]);
                if (!$res) {
                    throw new \Exception('转账支付保存失败');
                }
            } catch (\Exception $e) {
                Db::rollback();
                return self::error_return($e->getMessage());
            }
            Db::commit();
            OrderResult::add_order_log([
                'order_sn' => $order_sn,
                'order_id' => $order['order_id'],
                'remark' => '提交转账支付审核',
            ]);
        }
        if ($pay_way == 4) {
            $lock = $user_id . '_' . $order_sn;
            if (!LockService::logck_by_second($lock, 6, true)) {
                return self::error_return('正在处理，请勿重复提交');
            }
            $userMoney = (new User())->get_value(['user_id' => $user_id], 'credit');
            if ($userMoney < $order['order_pay_price']) {
                LockService::unlock($lock);
                return self::error_return('余额不足');
            }
            try {
                Db::startTrans();
                $creditAction = CreditService::credit_action($user_id, -$order['order_pay_price'], [
                    'order_sn' => $order_sn,
                    'remark' => '订单支付'
                ]);
                if (!$creditAction) {
                    throw new \Exception('余额扣除失败');
                }
                $upOrder = (new Order())->data_update(['order_id' => $order['order_id']], [
                    'pay_status' => 1,
                    'order_status' => 1,
                    'pay_price' => $order['order_pay_price'],
                    'pay_time' => date('Y-m-d H:i:s'),
                    'pay_type' => $pay_way,
                    'trans_no' => $trans_no ?? "",
                ]);
                if (!$upOrder) {
                    throw new \Exception('更新订单失败');
                }
            } catch (\Exception $e) {
                Db::rollback();
                LockService::unlock($lock);
                return self::error_return($e->getMessage());
            }
            Db::commit();
            LockService::unlock($lock);
        }
        $param = [];
        return self::success_return('支付成功', [
            'pay_way' => $pay_way,
            'param' => $param
        ]);
    }

    private function cashier_query_recharge($args)
    {
        $order_sn = $args['order_sn'] ?? '';
        if (!$order_sn) {
            return self::error_return('请选择订单');
        }
        $order = (new RechargeLog())->data_get(['order_sn' => $order_sn]);
        if (!$order) {
            return self::error_return('订单不存在');
        }
        if ($order['pay_status'] == 1) {
            return self::success_return('success', [
                'pay_status' => 1,
                'order_sn' => $order_sn,
                'order_amount' => $order['money'],
                'pay_method' => $order['pay_type'] == 2 ? 'alipay' : ($order['pay_type'] == 1 ? 'wechat' : 'transfer'),//支付方式：1=微信，2=支付宝，3=转账
            ]);
        }
        return self::success_return('success', [
            'pay_status' => $order['pay_status'],
            'order_sn' => $order_sn,
            'order_amount' => $order['money'],
            'pay_method' => $order['pay_type'] == 2 ? 'alipay' : ($order['pay_type'] == 1 ? 'wechat' : 'transfer'),//支付方式：1=微信，2=支付宝，3=转账
        ]);
    }

    // 收银台查询订单
    public function cashier_query($args)
    {
        $order_sn = $args['order_sn'] ?? '';
        if (!$order_sn) {
            return self::error_return('请选择订单');
        }
        if (str_starts_with($order_sn, 'REC')) {
            return $this->cashier_query_recharge($args);
        } else {
            $order = (new Order())->data_get(['order_sn' => $order_sn]);
        }
        if (!$order) {
            return self::error_return('订单不存在');
        }
        if ($order['order_status'] !== 0) {
            return self::success_return('success', [
                'pay_status' => $order['pay_status'],
                'order_sn' => $order_sn,
                'order_amount' => $order['order_pay_price'],
                'pay_method' => $order['pay_type'] == 2 ? 'alipay' : ($order['pay_type'] == 1 ? 'wechat' : 'transfer'),//支付方式：1=微信，2=支付宝，3=转账
            ]);
        } elseif ($order['pay_status'] == 1) {
            return self::success_return('success', [
                'pay_status' => 1,
                'order_sn' => $order_sn,
                'order_amount' => $order['order_pay_price'],
                'pay_method' => $order['pay_type'] == 2 ? 'alipay' : ($order['pay_type'] == 1 ? 'wechat' : 'transfer'),//支付方式：1=微信，2=支付宝，3=转账
            ]);
        }

        return self::success_return('success', [
            'pay_status' => $order['pay_status'],
            'order_sn' => $order_sn,
            'order_amount' => $order['order_pay_price'],
            'pay_method' => $order['pay_type'] == 2 ? 'alipay' : ($order['pay_type'] == 1 ? 'wechat' : 'transfer'),//支付方式：1=微信，2=支付宝，3=转账
        ]);
    }

    // 收银台余额支付
    private function cashier_pay_recharge($args)
    {
        $order_sn = $args['order_sn'] ?? '';
        if (!$order_sn) {
            return self::error_return('请选择订单');
        }
        $order = (new RechargeLog())->data_get(['order_sn' => $order_sn]);
        if (!$order) {
            return self::error_return('订单不存在');
        } elseif ($order['pay_status'] == 1) {
            return self::error_return('订单已支付');
        }
        $pay_method = $args['pay_method'] ?? '';// alipay/wechat
        if (!$pay_method) {
            return self::error_return('请选择支付方式');
        }
        if ($pay_method == 'alipay') {
            $form = (new PaymentService())->alipay([
                'order_sn' => $order_sn,
                'order_amount' => $order['money'],
                'subject' => '余额充值',
                'user_id' => $order['user_id'],
            ]);
            return self::success_return('success', [
                'order_sn' => $order_sn,
                'order_amount' => $order['money'],
                'formHtml' => $form,
            ]);
        } else {
            return self::error_return('暂不支持该支付方式');
        }
    }

    // 收银台支付
    public function cashier_pay($args)
    {
        $order_sn = $args['order_sn'] ?? '';
        if (!$order_sn) {
            return self::error_return('请选择订单');
        }
        if (str_starts_with($order_sn, 'REC')) {
            return $this->cashier_pay_recharge($args);
        }
        $order = (new Order())->data_get(['order_sn' => $order_sn]);
        if (!$order) {
            return self::error_return('订单不存在');
        } elseif ($order['order_status'] !== 0) {
            return self::error_return('订单状态不支持支付');
        } elseif ($order['pay_status'] == 1) {
            return self::error_return('订单已支付');
        }
        $pay_method = $args['pay_method'] ?? '';// alipay/wechat
        if (!$pay_method) {
            return self::error_return('请选择支付方式');
        }
        if ($pay_method == 'alipay') {
            $form = (new PaymentService())->alipay([
                'order_sn' => $order_sn,
                'order_amount' => $order['order_pay_price'],
                'subject' => '订单支付',
                'user_id' => $order['user_id'],
            ]);
            return self::success_return('success', [
                'order_sn' => $order_sn,
                'order_amount' => $order['order_pay_price'],
                'formHtml' => $form,
            ]);
        } else {
            return self::error_return('暂不支持该支付方式');
        }

    }
}
